package com.jeesite.modules.fl.service;

import java.util.Iterator;
import java.util.List;

import javax.validation.ConstraintViolationException;

import com.jeesite.common.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.validator.ValidatorUtils;
import com.jeesite.modules.fl.dao.ClinicDao;
import com.jeesite.modules.fl.dao.ClinicSettingDao;
import com.jeesite.modules.fl.entity.Clinic;
import com.jeesite.modules.fl.entity.ClinicSetting;
import com.jeesite.modules.sys.entity.Area;

@Service
@Transactional(readOnly=true)
public class ClinicService  extends CrudService<ClinicDao, Clinic>{
	
	@Autowired
	private ClinicSettingDao settingDao;
	
	/**
	 * 获取单条数据
	 * @param clinic
	 * @return
	 */
	@Override
	public Clinic get(Clinic clinic) {
		Clinic entity = super.get(clinic);
		if(!entity.getIsNewRecord()){
			ClinicSetting setting = new ClinicSetting();
			setting.setStatus("0");
			setting.setClinic(entity);
			List<ClinicSetting> settings = settingDao.findList(setting);
			entity.setDepartments(toString(settings));
		}
		return entity;
	}
	
	public Clinic getByName(String name) {
		List<Clinic> clinics = dao.findByName(name);
		if(clinics.isEmpty()){
			return null;
		}else{
			return clinics.get(0);
		}
	}
	
	public List<Area> getArea(String enterpriseId){
		return dao.getAreas(enterpriseId, null);
	}

	public List<Area> getArea(String enterpriseId, String allowSchedule){
		return dao.getAreas(enterpriseId, allowSchedule);
	}
	
	public List<Clinic> getClinic(String areaCode, String enterpriseId, String allowSchedule){
		if(enterpriseId == null || enterpriseId.isEmpty()){
			return dao.findByAreaCode(areaCode,allowSchedule);
		}else{
			return dao.findByLoginAreaCode(areaCode, enterpriseId,allowSchedule);
		}
	}
	
	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param clinic
	 * @return
	 */
	@Override
	public Page<Clinic> findPage(Page<Clinic> page, Clinic clinic) {
		return super.findPage(page, clinic);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param clinic
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(Clinic clinic) {
		super.save(clinic);
		ClinicSetting setting = new ClinicSetting();
		setting.setStatus("0");
		setting.setClinic(clinic);
		List<ClinicSetting> settings = settingDao.findList(setting);
		List<String> departments = toList(clinic.getDepartments());
		if(departments.size()>0){
			for(String department:departments){
				ClinicSetting st = new ClinicSetting();
				st.setStatus("0");
				st.setDepartment(department);
				st.setClinic(clinic);
				ClinicSetting result = contains(settings, st);
				if(result != null){
					settings.remove(result);
				}else{
					st.preInsert();
					settingDao.insert(st);
				}
			}
		}
		for(ClinicSetting set : settings){
			settingDao.delete(set);
		}
	}
	
	@SuppressWarnings("rawtypes")
	@Transactional(readOnly=false)
	public String importData(MultipartFile file, Boolean isUpdateSupport)
    {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        if(file == null)
            throw new ServiceException("请选择导入的数据文件！");
        ExcelImport ei = null;
        
        try
        {
        	ei = new ExcelImport(file, 2, Integer.valueOf(0));
        	List list = ei.getDataList(Clinic.class, new String[0]);
            for(Iterator iterator = list.iterator(); iterator.hasNext();)
            {
            	Clinic clinic = (Clinic)iterator.next();
                try
                {
                    Clinic c = getByName(clinic.getName());
                    if(c == null)
                    {
                        save(clinic);
                        successNum++;
                        successMsg.append((new StringBuilder()).append("<br/>").append(successNum).append("、诊所 ").append(clinic.getName()).append(" 导入成功").toString());
                    } else if(isUpdateSupport.booleanValue())
                    {
                    	clinic.setId(c.getId());
                        save(clinic);
                        successNum++;
                        successMsg.append((new StringBuilder()).append("<br/>").append(successNum).append("、诊所 ").append(clinic.getName()).append(" 更新成功").toString());
                    } else
                    {
                        failureNum++;
                        failureMsg.append((new StringBuilder()).append("<br/>").append(failureNum).append("、诊所 ").append(clinic.getName()).append(" 已存在").toString());
                    }
                }
                catch(Exception e)
                {
                    failureNum++;
                    String msg = (new StringBuilder()).append("<br/>").append(failureNum).append("、诊所 ").append(clinic.getName()).append(" 导入失败：").toString();
                    if(e instanceof ConstraintViolationException)
                    {
                        List messageList = ValidatorUtils.extractPropertyAndMessageAsList((ConstraintViolationException)e, ": ");
                        for(Iterator iterator1 = messageList.iterator(); iterator1.hasNext();)
                        {
                            String message = (String)iterator1.next();
                            msg = (new StringBuilder()).append(msg).append(message).append("; ").toString();
                        }

                    } else
                    {
                        msg = (new StringBuilder()).append(msg).append(e.getMessage()).toString();
                    }
                    failureMsg.append(msg);
                    logger.error(msg, e);
                }
            }

        }
        catch(Throwable throwable2)
        {
        	throwable2.printStackTrace();
        }
        finally
        {
            if(ei != null) 
            	ei.close();
        }
        if(failureNum > 0)
        {
            failureMsg.insert(0, (new StringBuilder()).append("很抱歉，导入失败！共 ").append(failureNum).append(" 条数据格式不正确，错误如下：").toString());
            throw new ServiceException(failureMsg.toString());
        } else
        {
            successMsg.insert(0, (new StringBuilder()).append("恭喜您，数据已全部导入成功！共 ").append(successNum).append(" 条，数据如下：").toString());
            return successMsg.toString();
        }
    }
	
	/**
	 * 更新状态
	 * @param clinic
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(Clinic clinic) {
		super.updateStatus(clinic);
	}
	
	/**
	 * 删除数据
	 * @param clinic
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(Clinic clinic) {
		super.delete(clinic);
		ClinicSetting setting = new ClinicSetting();
		setting.setClinic(clinic);
		settingDao.delete(setting);
	}
	
	private ClinicSetting contains(List<ClinicSetting> settings, ClinicSetting set){
		for(ClinicSetting setting: settings){
			if(setting.getDepartment().equals(set.getDepartment()) && setting.getClinic().getId().equals(set.getClinic().getId())){
				return setting;
			}
		}
		return null;
	}
	
	private List<String> toList(String settings){
		List<String> result = ListUtils.newArrayList();
		if(settings == null || settings.isEmpty()){
			return result;
		}
		String[] ss = settings.split(",");
		for(String s:ss){
			if(!s.isEmpty()){
				result.add(s);
			}
		}
		return result;
	}
	
	private String toString(List<ClinicSetting> settings){
		if(settings == null || settings.isEmpty()){
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for(ClinicSetting st : settings){
			sb.append(st.getDepartment()).append(",");
		}
		return sb.substring(0, sb.length()-1);
	}

	public void setListEngLang(List<Clinic> clinicList) {
		for (Clinic clinic : clinicList) {
			setEngLang(clinic);
		}
	}

	public void setEngLang(Clinic source_clinic){
		if(source_clinic==null || StringUtils.isBlank(source_clinic.getId())) return;
		Clinic clinic = get(new Clinic(source_clinic.getId()));
		if (clinic.getEnAddress() != null && !clinic.getEnAddress().isEmpty()) {
			source_clinic.setAddress(clinic.getEnAddress());
		}
		if (clinic.getEnBusiness() != null && !clinic.getEnBusiness().isEmpty()) {
			source_clinic.setBusinessDays(clinic.getEnBusiness());
		}
		if (clinic.getEnDescriptions() != null && !clinic.getEnDescriptions().isEmpty()) {
			source_clinic.setRemarks(clinic.getEnDescriptions());
		}
		if (clinic.getEnName() != null && !clinic.getEnName().isEmpty()) {
			source_clinic.setName(clinic.getEnName());
		}
	}
}
